package com.eunion.boot;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.eunion.core.common.JsonVo;
import com.google.gson.Gson;
//import com.google.gson.Gson;

/**
 * 处理异常.
 * 
 * @since 2017年1月1日
 */
//@Component
public class SysSimpleMappingExceptionResolver extends SimpleMappingExceptionResolver {

	public SysSimpleMappingExceptionResolver() {
		Properties mappings = new Properties();
		mappings.setProperty("org.springframework.security.access.AccessDeniedException", "admin/403");
		mappings.setProperty("NoSuchRequestHandlingMethodException", "404");
		mappings.setProperty("java.lang.Throwable", "500");
//		super.setExceptionMappings(mappings); // None by default
//		super.setDefaultErrorView("error"); // No default
//		super.setExceptionAttribute("ex"); // Default is "exception"
//		super.setWarnLogCategory("example.MvcLogger"); // No default
		super.setExceptionMappings(mappings);
	}

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		// Expose ModelAndView for chosen error view.  
		String viewName = determineViewName(ex, request);
		if (viewName != null) {// JSP格式返回  
			if (!(request.getHeader("accept").indexOf("application/json") > -1
			      || (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
				// 如果不是异步请求  
				// Apply HTTP status code for error views, if specified.  
				// Only apply it if we're processing a top-level request.  
				Integer statusCode = determineStatusCode(request, viewName);
				if (statusCode != null) {
					applyStatusCodeIfPossible(request, response, statusCode);
				}
				return getModelAndView(viewName, ex, request);
			} else {// JSON格式返回  
				try {
					JsonVo jv = new JsonVo(false, "系统异常");
					PrintWriter writer = response.getWriter();
					writer.write(new Gson().toJson(jv));
					writer.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return null;

			}
		} else {
			return null;
		}
	}
}
